package gdufs.lkl.calculator;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Map;

public class UnitConverterActivity extends AppCompatActivity {

    public static final String EXTRA_CONVERTER_TYPE = "converter_type";
    
    public static final int TYPE_CURRENCY = 0;
    public static final int TYPE_LENGTH = 1;
    public static final int TYPE_AREA = 2;
    public static final int TYPE_VOLUME = 3;
    public static final int TYPE_TEMPERATURE = 4;
    public static final int TYPE_SPEED = 5;
    public static final int TYPE_TIME = 6;
    public static final int TYPE_WEIGHT = 7;
    public static final int TYPE_NUMERAL = 8;
    
    private int converterType;
    private String[] fromUnits;
    private String[] toUnits;
    
    private Toolbar toolbar;
    private Spinner spinnerFrom;
    private Spinner spinnerTo;
    private EditText editTextValue;
    private TextView textViewResult;
    private LinearLayout layoutNumeralSystem;
    private TextView tvBinaryResult;
    private TextView tvOctalResult;
    private TextView tvDecimalResult;
    private TextView tvHexResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unit_converter);
        
        // 初始化视图
        initViews();
        
        // 获取转换类型
        converterType = getIntent().getIntExtra(EXTRA_CONVERTER_TYPE, TYPE_LENGTH);
        
        // 设置标题和单位数组
        setupConverterType();
        
        // 设置下拉菜单
        setupSpinners();
        
        // 如果是货币转换，尝试更新汇率
        if (converterType == TYPE_CURRENCY) {
            updateExchangeRates();
        }
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        spinnerFrom = findViewById(R.id.spinnerFrom);
        spinnerTo = findViewById(R.id.spinnerTo);
        editTextValue = findViewById(R.id.editTextValue);
        textViewResult = findViewById(R.id.textViewResult);
        layoutNumeralSystem = findViewById(R.id.layoutNumeralSystem);
        tvBinaryResult = findViewById(R.id.tvBinaryResult);
        tvOctalResult = findViewById(R.id.tvOctalResult);
        tvDecimalResult = findViewById(R.id.tvDecimalResult);
        tvHexResult = findViewById(R.id.tvHexResult);
        
        findViewById(R.id.buttonConvert).setOnClickListener(v -> convert());
        findViewById(R.id.buttonSwap).setOnClickListener(v -> swapUnits());
    }
    
    private void setupToolbar() {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        
        // 设置标题
        switch (converterType) {
            case TYPE_CURRENCY:
                getSupportActionBar().setTitle(R.string.currency_converter);
                break;
            case TYPE_LENGTH:
                getSupportActionBar().setTitle(R.string.length_converter);
                break;
            case TYPE_AREA:
                getSupportActionBar().setTitle(R.string.area_converter);
                break;
            case TYPE_VOLUME:
                getSupportActionBar().setTitle(R.string.volume_converter);
                break;
            case TYPE_TEMPERATURE:
                getSupportActionBar().setTitle(R.string.temperature_converter);
                break;
            case TYPE_SPEED:
                getSupportActionBar().setTitle(R.string.speed_converter);
                break;
            case TYPE_TIME:
                getSupportActionBar().setTitle(R.string.time_converter);
                break;
            case TYPE_WEIGHT:
                getSupportActionBar().setTitle(R.string.weight_converter);
                break;
            case TYPE_NUMERAL:
                getSupportActionBar().setTitle(R.string.numeral_converter);
                break;
        }
    }
    
    private void setupConverterType() {
        // 根据转换器类型设置相应的单位选项
        switch (converterType) {
            case TYPE_CURRENCY:
                fromUnits = getResources().getStringArray(R.array.currency_units);
                toUnits = getResources().getStringArray(R.array.currency_units);
                break;
            case TYPE_LENGTH:
                fromUnits = getResources().getStringArray(R.array.length_units);
                toUnits = getResources().getStringArray(R.array.length_units);
                break;
            case TYPE_AREA:
                fromUnits = getResources().getStringArray(R.array.area_units);
                toUnits = getResources().getStringArray(R.array.area_units);
                break;
            case TYPE_VOLUME:
                fromUnits = getResources().getStringArray(R.array.volume_units);
                toUnits = getResources().getStringArray(R.array.volume_units);
                break;
            case TYPE_TEMPERATURE:
                fromUnits = getResources().getStringArray(R.array.temperature_units);
                toUnits = getResources().getStringArray(R.array.temperature_units);
                break;
            case TYPE_SPEED:
                fromUnits = getResources().getStringArray(R.array.speed_units);
                toUnits = getResources().getStringArray(R.array.speed_units);
                break;
            case TYPE_TIME:
                fromUnits = getResources().getStringArray(R.array.time_units);
                toUnits = getResources().getStringArray(R.array.time_units);
                break;
            case TYPE_WEIGHT:
                fromUnits = getResources().getStringArray(R.array.weight_units);
                toUnits = getResources().getStringArray(R.array.weight_units);
                break;
            case TYPE_NUMERAL:
                fromUnits = getResources().getStringArray(R.array.numeral_units);
                toUnits = getResources().getStringArray(R.array.numeral_units);
                layoutNumeralSystem.setVisibility(View.VISIBLE);
                break;
            default:
                fromUnits = new String[]{"Unknown"};
                toUnits = new String[]{"Unknown"};
        }
    }
    
    private void setupSpinners() {
        ArrayAdapter<String> fromAdapter = new ArrayAdapter<>(this, 
                android.R.layout.simple_spinner_item, fromUnits);
        fromAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerFrom.setAdapter(fromAdapter);
        
        ArrayAdapter<String> toAdapter = new ArrayAdapter<>(this, 
                android.R.layout.simple_spinner_item, toUnits);
        toAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerTo.setAdapter(toAdapter);
        
        // 设置默认选择不同的单位
        if (toUnits.length > 1) {
            spinnerTo.setSelection(1);
        }
        
        // 为进制转换设置特殊监听
        if (converterType == TYPE_NUMERAL) {
            spinnerFrom.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    convert();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) { }
            });
        }
    }
    
    private void swapUnits() {
        if (converterType == TYPE_NUMERAL) {
            Toast.makeText(this, "进制转换不支持单位交换", Toast.LENGTH_SHORT).show();
            return;
        }
        
        int fromPosition = spinnerFrom.getSelectedItemPosition();
        int toPosition = spinnerTo.getSelectedItemPosition();
        
        spinnerFrom.setSelection(toPosition);
        spinnerTo.setSelection(fromPosition);
        
        String resultText = textViewResult.getText().toString();
        if (!TextUtils.isEmpty(resultText) && !resultText.equals("0") && 
                !TextUtils.isEmpty(editTextValue.getText())) {
            editTextValue.setText(resultText);
            convert();
        }
    }
    
    private void convert() {
        String valueStr = editTextValue.getText().toString().trim();
        if (TextUtils.isEmpty(valueStr)) {
            Toast.makeText(this, "请输入要转换的值", Toast.LENGTH_SHORT).show();
            return;
        }
        
        try {
            double value = Double.parseDouble(valueStr);
            String fromUnit = fromUnits[spinnerFrom.getSelectedItemPosition()];
            String toUnit = toUnits[spinnerTo.getSelectedItemPosition()];
            
            double result;
            switch (converterType) {
                case TYPE_CURRENCY:
                    result = convertCurrency(value, fromUnit, toUnit);
                    displayResult(result);
                    break;
                case TYPE_LENGTH:
                    result = convertLength(value, fromUnit, toUnit);
                    displayResult(result);
                    break;
                case TYPE_AREA:
                    result = convertArea(value, fromUnit, toUnit);
                    displayResult(result);
                    break;
                case TYPE_VOLUME:
                    result = convertVolume(value, fromUnit, toUnit);
                    displayResult(result);
                    break;
                case TYPE_TEMPERATURE:
                    result = convertTemperature(value, fromUnit, toUnit);
                    displayResult(result);
                    break;
                case TYPE_SPEED:
                    result = convertSpeed(value, fromUnit, toUnit);
                    displayResult(result);
                    break;
                case TYPE_TIME:
                    result = convertTime(value, fromUnit, toUnit);
                    displayResult(result);
                    break;
                case TYPE_WEIGHT:
                    result = convertWeight(value, fromUnit, toUnit);
                    displayResult(result);
                    break;
                case TYPE_NUMERAL:
                    convertNumeralSystem(valueStr, fromUnit);
                    break;
            }
        } catch (NumberFormatException e) {
            Toast.makeText(this, "无效的数值输入", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "转换错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    private void displayResult(double result) {
        DecimalFormat df = new DecimalFormat("0.########");
        df.setRoundingMode(RoundingMode.HALF_UP);
        textViewResult.setText(df.format(result));
    }
    
    // 汇率转换    // 存储最新的汇率数据
    private Map<String, Double> currentRates;
    private boolean isUpdatingRates = false;
    
    private double convertCurrency(double value, String fromUnit, String toUnit) {
        if (currentRates == null || currentRates.isEmpty()) {
            // 如果没有汇率数据，使用旧的固定汇率
            return convertCurrencyWithFixedRates(value, fromUnit, toUnit);
        }
        
        ExchangeRateService exchangeRateService = ExchangeRateService.getInstance(this);
        String fromCode = exchangeRateService.getCodeFromName(fromUnit);
        String toCode = exchangeRateService.getCodeFromName(toUnit);
        
        Double fromRate = currentRates.get(fromCode);
        Double toRate = currentRates.get(toCode);
        
        if (fromRate == null || toRate == null) {
            // 如果没有找到汇率，使用旧的固定汇率
            return convertCurrencyWithFixedRates(value, fromUnit, toUnit);
        }
        
        // 使用API获取的实时汇率进行转换
        return value * (toRate / fromRate);
    }
    
    private double convertCurrencyWithFixedRates(double value, String fromUnit, String toUnit) {
        // 使用固定汇率作为备用 (相对于1美元的汇率)
        double fromRate = getFixedCurrencyRate(fromUnit);
        double toRate = getFixedCurrencyRate(toUnit);
        
        // 先转换为美元，再转换为目标货币
        return value / fromRate * toRate;
    }
    
    private double getFixedCurrencyRate(String currency) {
        switch (currency) {
            case "人民币":
                return 7.18; // 1美元约等于7.18人民币 (2025年6月固定值)
            case "美元":
                return 1.0;
            case "欧元":
                return 0.87; // 1美元约等于0.87欧元
            case "英镑":
                return 0.74; // 1美元约等于0.74英镑
            case "日元":
                return 145.13; // 1美元约等于145日元
            case "韩元":
                return 1370.06; // 1美元约等于1370韩元
            case "港币":
                return 7.85; // 1美元约等于7.85港币
            default:
                return 1.0;
        }
    }
    
    // 长度转换
    private double convertLength(double value, String fromUnit, String toUnit) {
        // 转换为米为基准单位
        double valueInMeters = toMeters(value, fromUnit);
        
        // 从米转换为目标单位
        return fromMeters(valueInMeters, toUnit);
    }
    
    private double toMeters(double value, String unit) {
        switch (unit) {
            case "千米(km)":
                return value * 1000;
            case "米(m)":
                return value;
            case "厘米(cm)":
                return value * 0.01;
            case "毫米(mm)":
                return value * 0.001;
            case "微米(μm)":
                return value * 0.000001;
            case "英里(mi)":
                return value * 1609.344;
            case "码(yd)":
                return value * 0.9144;
            case "英尺(ft)":
                return value * 0.3048;
            case "英寸(in)":
                return value * 0.0254;
            default:
                return value;
        }
    }
    
    private double fromMeters(double meters, String unit) {
        switch (unit) {
            case "千米(km)":
                return meters / 1000;
            case "米(m)":
                return meters;
            case "厘米(cm)":
                return meters / 0.01;
            case "毫米(mm)":
                return meters / 0.001;
            case "微米(μm)":
                return meters / 0.000001;
            case "英里(mi)":
                return meters / 1609.344;
            case "码(yd)":
                return meters / 0.9144;
            case "英尺(ft)":
                return meters / 0.3048;
            case "英寸(in)":
                return meters / 0.0254;
            default:
                return meters;
        }
    }
    
    // 面积转换
    private double convertArea(double value, String fromUnit, String toUnit) {
        // 转换为平方米为基准单位
        double valueInSquareMeters = toSquareMeters(value, fromUnit);
        
        // 从平方米转换为目标单位
        return fromSquareMeters(valueInSquareMeters, toUnit);
    }
    
    private double toSquareMeters(double value, String unit) {
        switch (unit) {
            case "平方千米(km²)":
                return value * 1000000;
            case "公顷(ha)":
                return value * 10000;
            case "平方米(m²)":
                return value;
            case "平方厘米(cm²)":
                return value * 0.0001;
            case "平方毫米(mm²)":
                return value * 0.000001;
            case "平方英里(sq mi)":
                return value * 2589988.11;
            case "英亩(acre)":
                return value * 4046.86;
            case "平方码(sq yd)":
                return value * 0.836127;
            case "平方英尺(sq ft)":
                return value * 0.092903;
            case "平方英寸(sq in)":
                return value * 0.00064516;
            default:
                return value;
        }
    }
    
    private double fromSquareMeters(double squareMeters, String unit) {
        switch (unit) {
            case "平方千米(km²)":
                return squareMeters / 1000000;
            case "公顷(ha)":
                return squareMeters / 10000;
            case "平方米(m²)":
                return squareMeters;
            case "平方厘米(cm²)":
                return squareMeters / 0.0001;
            case "平方毫米(mm²)":
                return squareMeters / 0.000001;
            case "平方英里(sq mi)":
                return squareMeters / 2589988.11;
            case "英亩(acre)":
                return squareMeters / 4046.86;
            case "平方码(sq yd)":
                return squareMeters / 0.836127;
            case "平方英尺(sq ft)":
                return squareMeters / 0.092903;
            case "平方英寸(sq in)":
                return squareMeters / 0.00064516;
            default:
                return squareMeters;
        }
    }
    
    // 体积转换
    private double convertVolume(double value, String fromUnit, String toUnit) {
        // 转换为立方米为基准单位
        double valueInCubicMeters = toCubicMeters(value, fromUnit);
        
        // 从立方米转换为目标单位
        return fromCubicMeters(valueInCubicMeters, toUnit);
    }
    
    private double toCubicMeters(double value, String unit) {
        switch (unit) {
            case "立方米(m³)":
                return value;
            case "立方厘米(cm³)":
                return value * 0.000001;
            case "立方毫米(mm³)":
                return value * 1e-9;
            case "升(L)":
                return value * 0.001;
            case "毫升(mL)":
                return value * 0.000001;
            case "加仑(US gal)":
                return value * 0.00378541;
            case "夸脱(US qt)":
                return value * 0.000946353;
            case "品脱(US pt)":
                return value * 0.000473176;
            case "液量盎司(US fl oz)":
                return value * 0.0000295735;
            case "立方英尺(cu ft)":
                return value * 0.0283168;
            case "立方英寸(cu in)":
                return value * 0.0000163871;
            default:
                return value;
        }
    }
    
    private double fromCubicMeters(double cubicMeters, String unit) {
        switch (unit) {
            case "立方米(m³)":
                return cubicMeters;
            case "立方厘米(cm³)":
                return cubicMeters / 0.000001;
            case "立方毫米(mm³)":
                return cubicMeters / 1e-9;
            case "升(L)":
                return cubicMeters / 0.001;
            case "毫升(mL)":
                return cubicMeters / 0.000001;
            case "加仑(US gal)":
                return cubicMeters / 0.00378541;
            case "夸脱(US qt)":
                return cubicMeters / 0.000946353;
            case "品脱(US pt)":
                return cubicMeters / 0.000473176;
            case "液量盎司(US fl oz)":
                return cubicMeters / 0.0000295735;
            case "立方英尺(cu ft)":
                return cubicMeters / 0.0283168;
            case "立方英寸(cu in)":
                return cubicMeters / 0.0000163871;
            default:
                return cubicMeters;
        }
    }
    
    // 温度转换
    private double convertTemperature(double value, String fromUnit, String toUnit) {
        // 温度转换的公式比较特殊，需要单独处理
        double kelvin;
        
        // 先转换为开尔文
        switch (fromUnit) {
            case "摄氏度(°C)":
                kelvin = value + 273.15;
                break;
            case "华氏度(°F)":
                kelvin = (value + 459.67) * 5/9;
                break;
            case "开尔文(K)":
                kelvin = value;
                break;
            default:
                kelvin = value;
        }
        
        // 从开尔文转换为目标单位
        switch (toUnit) {
            case "摄氏度(°C)":
                return kelvin - 273.15;
            case "华氏度(°F)":
                return kelvin * 9/5 - 459.67;
            case "开尔文(K)":
                return kelvin;
            default:
                return kelvin;
        }
    }
    
    // 速度转换
    private double convertSpeed(double value, String fromUnit, String toUnit) {
        // 转换为米/秒为基准单位
        double valueInMeterPerSecond = toMeterPerSecond(value, fromUnit);
        
        // 从米/秒转换为目标单位
        return fromMeterPerSecond(valueInMeterPerSecond, toUnit);
    }
    
    private double toMeterPerSecond(double value, String unit) {
        switch (unit) {
            case "米/秒(m/s)":
                return value;
            case "千米/小时(km/h)":
                return value / 3.6;
            case "英里/小时(mph)":
                return value * 0.44704;
            case "英尺/秒(ft/s)":
                return value * 0.3048;
            case "节(knot)":
                return value * 0.514444;
            case "光速(c)":
                return value * 299792458;
            default:
                return value;
        }
    }
    
    private double fromMeterPerSecond(double meterPerSecond, String unit) {
        switch (unit) {
            case "米/秒(m/s)":
                return meterPerSecond;
            case "千米/小时(km/h)":
                return meterPerSecond * 3.6;
            case "英里/小时(mph)":
                return meterPerSecond / 0.44704;
            case "英尺/秒(ft/s)":
                return meterPerSecond / 0.3048;
            case "节(knot)":
                return meterPerSecond / 0.514444;
            case "光速(c)":
                return meterPerSecond / 299792458;
            default:
                return meterPerSecond;
        }
    }
    
    // 时间转换
    private double convertTime(double value, String fromUnit, String toUnit) {
        // 转换为秒为基准单位
        double valueInSeconds = toSeconds(value, fromUnit);
        
        // 从秒转换为目标单位
        return fromSeconds(valueInSeconds, toUnit);
    }
    
    private double toSeconds(double value, String unit) {
        switch (unit) {
            case "纳秒(ns)":
                return value * 1e-9;
            case "微秒(μs)":
                return value * 1e-6;
            case "毫秒(ms)":
                return value * 0.001;
            case "秒(s)":
                return value;
            case "分钟(min)":
                return value * 60;
            case "小时(h)":
                return value * 3600;
            case "天(day)":
                return value * 86400;
            case "周(week)":
                return value * 604800;
            case "月(30天)":
                return value * 2592000;
            case "年(365天)":
                return value * 31536000;
            default:
                return value;
        }
    }
    
    private double fromSeconds(double seconds, String unit) {
        switch (unit) {
            case "纳秒(ns)":
                return seconds / 1e-9;
            case "微秒(μs)":
                return seconds / 1e-6;
            case "毫秒(ms)":
                return seconds / 0.001;
            case "秒(s)":
                return seconds;
            case "分钟(min)":
                return seconds / 60;
            case "小时(h)":
                return seconds / 3600;
            case "天(day)":
                return seconds / 86400;
            case "周(week)":
                return seconds / 604800;
            case "月(30天)":
                return seconds / 2592000;
            case "年(365天)":
                return seconds / 31536000;
            default:
                return seconds;
        }
    }
    
    // 重量转换
    private double convertWeight(double value, String fromUnit, String toUnit) {
        // 转换为千克为基准单位
        double valueInKilograms = toKilograms(value, fromUnit);
        
        // 从千克转换为目标单位
        return fromKilograms(valueInKilograms, toUnit);
    }
    
    private double toKilograms(double value, String unit) {
        switch (unit) {
            case "吨(t)":
                return value * 1000;
            case "千克(kg)":
                return value;
            case "克(g)":
                return value * 0.001;
            case "毫克(mg)":
                return value * 1e-6;
            case "微克(μg)":
                return value * 1e-9;
            case "英磅(lb)":
                return value * 0.453592;
            case "盎司(oz)":
                return value * 0.0283495;
            case "石(st)":
                return value * 6.35029;
            case "短吨(US t)":
                return value * 907.185;
            case "长吨(UK t)":
                return value * 1016.05;
            default:
                return value;
        }
    }
    
    private double fromKilograms(double kilograms, String unit) {
        switch (unit) {
            case "吨(t)":
                return kilograms / 1000;
            case "千克(kg)":
                return kilograms;
            case "克(g)":
                return kilograms / 0.001;
            case "毫克(mg)":
                return kilograms / 1e-6;
            case "微克(μg)":
                return kilograms / 1e-9;
            case "英磅(lb)":
                return kilograms / 0.453592;
            case "盎司(oz)":
                return kilograms / 0.0283495;
            case "石(st)":
                return kilograms / 6.35029;
            case "短吨(US t)":
                return kilograms / 907.185;
            case "长吨(UK t)":
                return kilograms / 1016.05;
            default:
                return kilograms;
        }
    }
    
    // 进制转换
    private void convertNumeralSystem(String valueStr, String fromUnit) {
        try {
            int radix = getRadixFromUnit(fromUnit);
            long value;
            
            // 解析输入值
            if ("十六进制".equals(fromUnit)) {
                value = Long.parseLong(valueStr.replace("0x", "").toUpperCase(), 16);
            } else if ("二进制".equals(fromUnit)) {
                value = Long.parseLong(valueStr.replace("0b", ""), 2);
            } else if ("八进制".equals(fromUnit)) {
                value = Long.parseLong(valueStr.replace("0", ""), 8);
            } else {
                value = Long.parseLong(valueStr);
            }
            
            // 显示各种进制的结果
            tvBinaryResult.setText("0b" + Long.toBinaryString(value));
            tvOctalResult.setText("0" + Long.toOctalString(value));
            tvDecimalResult.setText(Long.toString(value));
            tvHexResult.setText("0x" + Long.toHexString(value).toUpperCase());
            
            // 显示主结果
            textViewResult.setText(Long.toString(value));
        } catch (NumberFormatException e) {
            Toast.makeText(this, "无效的" + fromUnit + "输入", Toast.LENGTH_SHORT).show();
        }
    }
    
    private int getRadixFromUnit(String unit) {
        switch (unit) {
            case "二进制":
                return 2;
            case "八进制":
                return 8;
            case "十进制":
                return 10;
            case "十六进制":
                return 16;
            default:
                return 10;
        }
    }
    
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    // 更新汇率数据
    private void updateExchangeRates() {
        if (isUpdatingRates) {
            return;
        }
        
        isUpdatingRates = true;
        ExchangeRateService exchangeRateService = ExchangeRateService.getInstance(this);
        
        exchangeRateService.updateRatesIfNeeded(new ExchangeRateService.RatesCallback() {
            @Override
            public void onRatesUpdated(Map<String, Double> rates) {
                currentRates = rates;
                isUpdatingRates = false;
                
                // 更新完汇率后，如果有输入值，则重新计算结果
                runOnUiThread(() -> {
                    String input = editTextValue.getText().toString();
                    if (!TextUtils.isEmpty(input)) {
                        try {
                            double value = Double.parseDouble(input);
                            convert();
                        } catch (NumberFormatException e) {
                            // 忽略不合法的输入
                        }
                    }
                });
            }

            @Override
            public void onError(String errorMessage) {
                isUpdatingRates = false;
                runOnUiThread(() -> {
                    Toast.makeText(UnitConverterActivity.this, 
                            "获取汇率失败，使用默认汇率", Toast.LENGTH_SHORT).show();
                });
            }
        });
    }
}
